import axios from 'axios';
import {
  Message
} from 'element-ui';
let apiBaseUrl = process.env.VUE_APP_API_URL;
// 通用公用方法
const req = (method, url, params) => {
  return new Promise((resolve, reject) => {
    axios({
        method: method,
        url: apiBaseUrl + url,
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        },
        data: params,
        traditional: true,
        transformRequest: [
          function(data) {
            let ret = ''
            for (let it in data) {
              ret +=
                encodeURIComponent(it) +
                '=' +
                encodeURIComponent(data[it]) +
                '&'
            }
            return ret
          }
        ]
      }).then(res => {
        resolve(res.data);
      })
      .catch(err => {
        let msg="";
        if(!err.response){
          msg='未知错误'
        }else{
          msg = '请求失败,错误码:' + err.response.status+",信息:"+(err.response.data&&err.response.data.message?err.response.data.message:"")
          if (err.response.status == 401) {
            msg = '登录失效，请重新登录系统'
          }else if(err.response.status == 403){
            msg='无权限，请联系管理员'
          }
        }
        Message({
          message: msg,
          type: 'error'
        });
        reject(err)
      })
  });
};

const json = (method, url, params) => {
  return new Promise((resolve, reject) => {
    axios({
        method: method,
        url: apiBaseUrl + url,
        headers: {
          'Content-Type': 'application/json'
        },
        data: params,
        traditional: true,
      }).then(res => {
        resolve(res.data);
      })
      .catch(err => {
        let msg = '请求失败:' + err
        if (err.response && err.response.status == 401) {
          msg = '登录失效，请重新登录系统'
        }
        Message({
          message: msg,
          type: 'error'
        });
        reject(err)
      })
  });
};


export {
  req,
  json
}
